package com.gpt.article.controller;

import java.io.*;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.document.ExportWordService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ZipUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.GptGenArticle;
import com.gpt.article.service.IGptGenArticleService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文章生成Controller
 *
 * @author zhuzi
 * @date 2023-10-24
 */
@RestController
@RequestMapping("/article/genArticle")
public class GptGenArticleController extends BaseController {
    @Autowired
    private IGptGenArticleService gptGenArticleService;

    /**
     * 查询文章生成列表
     */
    @PreAuthorize("@ss.hasPermi('article:genArticle:list')")
    @GetMapping("/list")
    public TableDataInfo list(GptGenArticle gptGenArticle) {
        startPage();
        List<GptGenArticle> list = gptGenArticleService.selectGptGenArticleList(gptGenArticle);
        return getDataTable(list);
    }

    /**
     * 导出文章生成列表
     */
    @PreAuthorize("@ss.hasPermi('article:genArticle:export')")
    @Log(title = "文章生成", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GptGenArticle gptGenArticle) throws IOException {
//        List<GptGenArticle> list = gptGenArticleService.selectGptGenArticleList(gptGenArticle);
        List<GptGenArticle> list = gptGenArticleService.selectExportGptGenArticleList(gptGenArticle);
        System.out.println(list.size());
//        String baseUppath = RuoYiConfig.getProfile()
        String exportWordZip = RuoYiConfig.getProfile() + "/zip";
        String exportWordPath = RuoYiConfig.getProfile() + "/word";
        deleteDirectoryLegacyIO(new File(exportWordPath));
        if (!new File(exportWordZip).exists()) {
            new File(exportWordZip).mkdirs();
        }
        //先清空
        for (GptGenArticle genArticle : list) {
            String title = genArticle.getTitle();
            String content = genArticle.getArtContent();
            String wordName = title.replaceAll("[/\\\\:*?|]", ".");
            wordName = wordName.replaceAll("[\"<>]", "'");
            try {
                String wordPath = exportWordPath + "/" + wordName + ".docx";
                new ExportWordService().exportWord(title, content, wordPath);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("error::" + e.getMessage());
            }
        }

        //打包成zip
        String name = "doc-" + DateUtils.dateTime() + ".zip";
        String zipPath = exportWordZip + "/" + name;
        //线程停止10s 计算包大小
        try {
            ZipUtils.createZipFileOfDirectory(new File(exportWordPath), new File(zipPath));
        } catch (Exception e) {
            System.out.println("错误信息 ： " + e.getMessage());
        }

        OutputStream os = response.getOutputStream();
        // 设置导出的内容是doc
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + name);
        ZipUtils.download(response, new File(zipPath));
//        WordUtil
//        ExcelUtil<GptGenArticle> util = new ExcelUtil<GptGenArticle>(GptGenArticle.class);
//        util.exportExcel(response, list, "文章生成数据");
    }


    /**
     * 获取文章生成详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:genArticle:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(gptGenArticleService.selectGptGenArticleById(id));
    }

    /**
     * 新增文章生成
     */
    @PreAuthorize("@ss.hasPermi('article:genArticle:add')")
    @Log(title = "文章生成", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GptGenArticle gptGenArticle) {
        return toAjax(gptGenArticleService.insertGptGenArticle(gptGenArticle));
    }

    /**
     * 修改文章生成
     */
    @PreAuthorize("@ss.hasPermi('article:genArticle:edit')")
    @Log(title = "文章生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GptGenArticle gptGenArticle) {
        return toAjax(gptGenArticleService.updateGptGenArticle(gptGenArticle));
    }

    /**
     * 删除文章生成
     */
    @PreAuthorize("@ss.hasPermi('article:genArticle:remove')")
    @Log(title = "文章生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(gptGenArticleService.deleteGptGenArticleByIds(ids));
    }


    /**
     * 查询文章生成列表
     */
    @GetMapping("/detail/{urlMd5}")
    public Map<String, Object> list(@PathVariable("urlMd5") String urlMd5) {
        Map<String, Object> map = gptGenArticleService.getAticleMap(urlMd5);
        return map;
    }


    private void deleteDirectoryLegacyIO(File file) {

        File[] list = file.listFiles();  //无法做到list多层文件夹数据
        if (list != null) {
            for (File temp : list) {     //先去递归删除子文件夹及子文件
                deleteDirectoryLegacyIO(temp);   //注意这里是递归调用
            }
        }

        if (file.delete()) {     //再删除自己本身的文件夹
            System.out.printf("删除成功 : %s%n", file);
        } else {
            System.err.printf("删除失败 : %s%n", file);
        }
    }

}
